/**
 * FileName: answer_1
 * Author:   why
 * Date:     2019/3/13 11:39
 * Description:
 */
package algorithm.leetcode.problem_2;

public class answer_1 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            //创建新结点
            ListNode l3 = new ListNode(0);
            ListNode l4 = l3;
            //存储余数
            int bit = 0;
            while (l1 != null || l2 != null) {
                int x = (l1 != null) ? l1.val : 0;
                int y = (l2 != null) ? l2.val : 0;
                int sum = x + y + bit;
                bit = sum / 10;
                //把相加的数进行新的结点存放
                l4.next = new ListNode(sum % 10);
                //切到新的结点
                l4 = l4.next;
                if (l1 != null) {
                    l1 = l1.next;
                }
                if (l2 != null) {
                    l2 = l2.next;
                }
                if (bit > 0) {
                    l4.next = new ListNode(bit);
                }
            }
            //默认创建的第一个结点是0 所以把之后的结点返回
            return l3.next;
        }
    }
}
